<!-- 越减越便宜升级版 -->
<template>
	<view class="container">
		<view class="inner">
			<view class="award-row reg">
				<image class="my-award" @click="onJumpMyAward" src="https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/system/5abc19ff-fcb2-4092-9b81-eb169614af81.png" mode="widthFix" style="width: 200rpx;"></image>
				<view v-if="limitComputed" class="limit-tip fs12">{{ limitComputed  }}</view>
				<view class="left">
					<view class="price fb">
						<text>￥</text>
						<text>{{ vdata.activityAward.A.awardPrice || 0 }}</text>
					</view>
					<view class="threshold fs12 color6">
						满{{ vdata.activityAward.A.payAmount || 0 }}可用
					</view>
				</view>
				<view class="middle">
					<view class="remark fs12">无门槛权益券</view>
					<view class="remain">
						<view class="num fs12">已抢{{ percentComputed }}%</view>
						<view class="process-container">
							<view class="process-bar" :style="{ width: `${100 - percentComputed}%` }"></view>
							<view class="process-bar-dot"></view>
						</view>
					</view>
				</view>
				<view class="right">
					<button class="btn" plain @click="activityTakePartIn(vdata.activityAward.A.awardId,vdata.activityAward.A.awardType,'A')">立即领取</button>
				</view>
			</view>
			<view class="auth-title"></view>
			<view class="award-row auth">
				<view class="award-item">
					<view class="award-type fs12">美宿、美景类</view>
					<view class="award-price fb">
						<text>￥</text>
						<text>{{ vdata.activityAward.B.awardPrice || 0 }}</text>
					</view>
					<view class="award-desc fs12 color6">满{{ vdata.activityAward.B.payAmount || 0 }}元立减{{ vdata.activityAward.B.awardPrice || 0 }}元</view>
					<button class="btn" @click="activityTakePartIn(vdata.activityAward.B.awardId,vdata.activityAward.B.awardType,'B')">立即领取</button>
				</view>
				<view class="award-item">
					<view class="award-type fs12">美食类</view>
					<view class="award-price fb">
						<text>￥</text>
						<text>{{ vdata.activityAward.C.awardPrice || 0 }}</text>
					</view>
					<view class="award-desc fs12 color6">满{{ vdata.activityAward.C.payAmount || 0 }}元立减{{ vdata.activityAward.C.awardPrice || 0 }}元</view>
					<button class="btn" @click="activityTakePartIn(vdata.activityAward.C.awardId,vdata.activityAward.C.awardType,'C')">立即领取</button>
				</view>
			</view>
		</view>
	</view>
	<!-- 授权登录弹窗 -->
	<gzLoginPopup ref="gzLoginPopupRef" v-model:isLogin="vdata.isLogin" @isLoginCallback="isLoginCallback"></gzLoginPopup>
	<!-- 结果弹窗 -->
	<uni-popup ref="resultPopupRef" :mask-click="false">
		<view class="popup-container">
			<view class="popup-close" @click="onClosePopupHandler"></view>
			<view class="popup-inner" :style="[popupBgComputed]">
				<rich-text class="popup-result" :nodes="takePartResult"></rich-text>
				<button class="popup-btn" :class="{ icon: true }" plain @click="onPopupClickHandler">{{ currentStatus === 'NO_AUTH' ? '前往认证' : '前往使用' }}</button>
			</view>
		</view>
	</uni-popup>
</template>

<script setup>
	import { ref, reactive, getCurrentInstance, computed } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { $activityTakePartIn, $fansDetail, $getAwardList, $getActivityAwardNum } from '@/http/apiManager.js'
	import storageManage from '@/util/storageManage.js'
	import numberUtil from '@/util/numberUtil.js'
	
	const { $infoBox } = getCurrentInstance().appContext.config.globalProperties

	// 登录
	const gzLoginPopupRef = ref()
	// 结果
	const resultPopupRef = ref()

	// 数据源
	const vdata = reactive({
		isLogin: false,	// 用户是否登录
		fansInfo: {},	// 用户详情
		activityId: '', // 活动id
		activityDetail: {}, // 活动详情
		activityAward: { A:{}, B:{}, C:{} },	// 活动奖品信息ABC
		activityAwardADetail: {},	// 奖品A的详细信息 限制类型限制次数 以及 进度条
	})
	
	onLoad(async ({ activityId, activityDetail, activityChannelId }) => {
		vdata.isLogin = storageManage.isLogin()
		vdata.activityId = activityId
		vdata.activityDetail = JSON.parse(decodeURIComponent(activityDetail))
		// 标题更改为活动名称
		uni.setNavigationBarTitle({
			title: vdata.activityDetail.activityName || '新粉U享'
		})
		// 活动数据处理
		await activityDataHandler(activityId)
		// 活动拦截--登录、状态
		// 判断活动是否过期
		if (vdata.activityDetail.state !== 4){
			$infoBox.toast('当前活动已下线，正在返回首页！',{ duration: 2000, mask: true })
			setTimeout(() => {
				uni.switchTab({
					url: '/pages/index/index'
				})
			},2000)
			return
		}
	})
	
	onShow(async () => {
		// 已登录 但未拉取用户详情 需要拉取用户详情
		if(!storageManage.userInfo()){
			const { bizData:fansInfo } = await $fansDetail()
			Object.assign(vdata.fansInfo,fansInfo)
		}else{	// 存在用户详情
			Object.assign(vdata.fansInfo,storageManage.userInfo())
		}
	})
	
	
	// 弹窗背景map
	const POPUP_BG_MAP = {
		// 未实名背景
		NO_AUTH: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/henan/activity/e7e00940-5cf4-418c-aaee-43b854097cba.png',
		// 失败背景（很遗憾）
		FAIL: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/henan/activity/3c4733a5-4754-452b-a20c-2fe954cc1f26.png',
		// 成功背景（领取到）
		SUCCESS: 'https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/henan/activity/403b1470-eac1-4a7e-ab29-151a0842e076.png'
	}
	const currentStatus = ref('SUCCESS')
	const popupBgComputed = computed(() => {
		return { 'background-image': `url(${POPUP_BG_MAP[currentStatus.value]})` }
	})
	
	// 跳转我的福券
	function onJumpMyAward(){
		uni.navigateTo({
			url: '/pageUser/myCoupon/index?couponState=0&tabCurrent=1'
		})
	}
	
	// 打开弹窗事件 type SUCCESS FAIL NO_AUTH
	function onOpenPopupHandler(type){
		currentStatus.value = type
		resultPopupRef.value.open()
	}
	
	// 关闭结果弹窗
	function onClosePopupHandler(){
		resultPopupRef.value.close()
	}
	
	// 限量处理
	const limitComputed = computed(() => {
		const { periodType, periodTimes } = vdata.activityAwardADetail
		const periodTypeMap = {
			0: false,
			1: '日限量',
			2: '周限量',
			3: '月限量'
		}
		if(periodTypeMap[periodType]){
			return periodTypeMap[periodType] + periodTimes
		}
		return false
	})
	
	// 百分百处理
	const percentComputed = computed(() => {
		const { currentPeriodTimes, periodTimes } = vdata.activityAwardADetail
		if(periodTimes){
			return numberUtil.computeNumber(currentPeriodTimes,'/',periodTimes).next('*',100).toFloatNumber(2)
		}
		return 0
	})
	
	async function activityDataHandler(activityId){
		uni.showLoading({ title: '加载中...' })
		await getAwardListHandler(activityId)
		await getActivityAwardNum(activityId)
		uni.hideLoading()
	}
	
	// 获取活动奖品列表
	async function getAwardListHandler(activityId){
		const { bizData } = await $getAwardList({ activityId })
		// 数据处理
		bizData.forEach(item => {
			vdata.activityAward[item.remark] = { 
				...item,
				awardPrice: numberUtil.computeNumber(item.awardPrice,'/',100).result,
				payAmount: numberUtil.computeNumber(item.payAmount,'/',100).result
			}
		})
	}
	
	// 查询A奖品数量信息	payload:{activityId,awardId,awardType}
	async function getActivityAwardNum(activityId){
		const { awardId, awardType } = vdata.activityAward.A
		const payload = {
			activityId,
			awardId,
			awardType
		}
		const { bizData } = await $getActivityAwardNum(payload)
		vdata.activityAwardADetail = bizData
	}
	
	// 参与结果
	const takePartResult = ref('')
	// 参与活动
	async function activityTakePartIn(awardId,awardType,remark){
		// BC券校验实名
		if(remark === 'B' || remark === 'C'){
			if(vdata.fansInfo.isAuth !== 0){
				takePartResult.value = '您还未成为实名认证会员'
				// 未实名 给出引导实名弹框
				onOpenPopupHandler('NO_AUTH')
				return
			}
		}
		// 领取结果组装
		const { payAmount, awardPrice } = vdata.activityAward[remark]
		let tempResult = ''
		if(remark === 'A'){
			tempResult = `<div class="popup-result">无门槛<span style="color:#FF2150">“满${payAmount}减${awardPrice}”</span>权益券</div>`
		}else if(remark === 'B'){
			tempResult = `<div class="popup-result">美宿、美景类<span style="color:#FF2150">“满${payAmount}减${awardPrice}”</span>平台券</div>`
		}else {
			tempResult = `<div class="popup-result">美食类<span style="color:#FF2150">“满${payAmount}减${awardPrice}”</span>平台券</div>`
		}
		takePartResult.value = tempResult
		uni.showLoading({ title: '加载中...' })
		await $activityTakePartIn({
			activityId: vdata.activityId,
			activityTemplateNo: vdata.activityDetail.activityTemplateNo,
			awardId: awardId,
			awardType: awardType
		})
		// 领取成功后刷新A券信息
		await getActivityAwardNum(vdata.activityId)
		uni.hideLoading()
		onOpenPopupHandler('SUCCESS')
	}
	
	// 弹窗点击事件
	function onPopupClickHandler(){
		if(currentStatus.value === 'NO_AUTH'){	// 未认证 跳转实名认证页面
			uni.navigateTo({
				url: `/pageUser/realName/index?activityId=${vdata.activityId}&activityTemplateNo=${vdata.activityDetail.activityTemplateNo}`,
				success() {	// 跳转成功 关闭弹窗
					onClosePopupHandler()
				}
			})
		}else if(currentStatus.value === 'SUCCESS'){	// 领券成功 跳转郑好邮
			uni.navigateBackMiniProgram({
				extraData: {	// 携带参数
					isShow: true,	// 领券成功标识
				},
				success() {	// 跳转成功 关闭弹窗
					onClosePopupHandler()
				}
			})
		}else{ // 关闭弹窗
			onClosePopupHandler()
		}
	}
	
	// 导航栏左侧点击事件
	function onClickLeftHandler(){
		uni.navigateBack({
			fail() {
				uni.switchTab({
					url: '/pages/index/index'
				})
			}
		})
	}
	
	/**
	 * 登录回调
	 */
	function isLoginCallback(){
		if(!vdata.isLogin){
			$infoBox.toast('登录失败，无法正常参与活动！')
		}else{
			// 登陆成功后去处理历史消息
		}
	}

</script>

<style lang="less" scoped>
	@bg-theme-color: #EBFF94;
	@price-color: #FB344A;	// 金额字体颜色
	// 公共样式
	.btn{
		margin: initial;
		padding: initial;
		border-radius: 45rpx;
		background: linear-gradient(to right,#FF2189,#FF225A);
		color: #fff;
		font-size: 24rpx;
		border: none;
	}
	.fs12{
		font-size: 24rpx;
	}
	.color6{
		color: #666;
	}
	.fb{
		font-weight: bold;
	}
	// 结果弹窗
	.popup-container{
		position: relative;
		.popup-close{
			width: 70rpx;
			height: 70rpx;
			position: absolute;
			top: -70rpx;
			right: 0;
			background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/henan/activity/843d4fe7-5f06-4e83-a90b-8db473d7ff99.png') no-repeat left top / 100%;
		}
		.popup-inner{
			width: 524rpx;
			height: 458rpx;
			background-size: 100%;
			background-repeat: no-repeat;
			background-position: left top;
			text-align: center;
			padding: 234rpx 36rpx 36rpx;
			box-sizing: border-box;
			.popup-result{
				color: #333;
				font-size: 34rpx;
				.mark{
					color: #FF2150;
				}
			}
			.popup-btn{
				padding: 20rpx 70rpx;
				margin: 0;
				font-size: 40rpx;
				background: linear-gradient(to right,#B4E729,#E0FE01);
				border-radius: 45rpx;
				color: #fff;
				border: none;
				display: inline-block;
				line-height: 1;
				margin-top: 44rpx;
				
				// &.icon{
				// 	&::after{
				// 		content: '';
				// 		display: inline-block;
				// 		width: 48rpx;
				// 		height: 48rpx;
				// 		background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/henan/activity/de316827-368d-4137-a684-2124198de2f9.png') no-repeat left top / 100%;
				// 	}
				// }
			}
		}
	}
	.container {
		overflow: hidden; // 解决子元素margin影响父元素
		width: 100%;
		min-height: 100vh;
		position: relative;
		background-image: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/henan/activity/fb12b2ef-e179-4d9e-86a9-f40d58e2bf2d.png');
		background-color: @bg-theme-color;
		background-repeat: no-repeat;
		background-position: 0 -44px;
		background-size: 100%;
		
		.inner{
			padding: 470rpx 24rpx 120rpx;
			box-sizing: border-box;
		}
		
		.award-row{
			position: relative;
			box-sizing: border-box;
			&.reg{
				width: 100%;
				height: 346rpx;
				padding: 152rpx 64rpx 46rpx 52rpx;	// 固定卡券信息位置
				background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/system/1b9cf409-54bf-45c9-9c10-750d95363a82.png') no-repeat left top / 100%;
				display: flex;
				align-items: center;
				.my-award{
					position: absolute;
					top: -66rpx;
					right: 0;
				}
				.limit-tip{
					min-width: 125rpx;
					height: 50rpx;
					box-sizing: border-box;
					padding-left: 30rpx;
					padding-right: 10rpx;
					line-height: 1.8;
					background: url(https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/henan/activity/5ffeb7c5-1c42-4c7d-a7d3-140da3cc1542.png) no-repeat left top / 100% 100%;
					position: absolute;
					top: 128rpx;
					left: 34rpx;
				}
				.left{
					width: 168rpx;
					padding-left: 20rpx;
					box-sizing: border-box;
					text-align: center;
					.price{
						color: @price-color;
						text{
							&:nth-child(2){
								font-size: 48rpx;
							}
						}
					}
				}
				.middle{
					flex-grow: 1;
					text-align: left;
					padding-left: 30rpx;
					.remark{
						color: #333333;
					}
					.remain{
						width: 100%;
						margin-top: 12rpx;
						.num{
							color: @price-color;
						}
						.process-container{
							margin-top: 8rpx;
							width: 100%;
							background: #FDE4EA;
							border-radius: 25rpx;
							height: 14rpx;
							overflow: hidden;
							display: flex;
							justify-content: flex-start;
							align-items: center;
							.process-bar{
								// width: 76%;
								height: 100%;
								background-color: @price-color;
							}
							.process-bar-dot{
								width: 14rpx;
								height: 14rpx;
								background-color: @price-color;
								border: 2rpx solid #fff;
								border-radius: 50%;
								position: relative;
								left: -2rpx;
								box-sizing: border-box;
							}
						}
					}
				}
				.right{
					width: 194rpx;
					flex-shrink: 0;
					text-align: center;
					.btn{
						width: 148rpx;
						height: 56rpx;
						text-align: center;
						line-height: 56rpx;
						margin: 0 auto;
					}
				}
			}
			&.auth{
				width: 100%;
				height: 467rpx;
				background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/system/4785c408-8fe6-45d5-9ac6-5564616085d9.png') no-repeat left top / 100%;
				padding: 52rpx 36rpx 36rpx;
				display: flex;
				gap: 22rpx;
				.award-item{
					flex: 1;
					border: #FF7D89 12rpx solid;
					border-radius: 12rpx;
					padding: 70rpx 16rpx 44rpx;
					position: relative;
					background: linear-gradient(to top, #FDEDF5 5%, #FDEDF5 10%, #FEF3F8 15%, transparent 30%);
					text-align: center;
					.award-type{
						position: absolute;
						right: 0;
						top: 0;
						padding: 8rpx 20rpx;
						border-radius: 0 0 0 12rpx;
					}
					.award-price{
						color: @price-color;
						text{
							&:nth-child(2){
								font-size: 72rpx;
							}
						}
					}
					.award-desc{
						margin-bottom: 48rpx;
					}
					&:nth-child(1){
						.award-type{
							background: #E6EFED;
							color: #006548;
						}
					}
					&:nth-child(2){
						.award-type{
							background: #FFF5E6;
							color: #FF9501;
						}
					}
				}
			}
		}
		.auth-title{
			width: 396rpx;
			height: 98rpx;
			margin: 40rpx auto 0;
			background: url('https://jdyd-marketing-public.oss-cn-hangzhou.aliyuncs.com/system/faa18b9d-6522-4e28-91bc-95ff40c07ead.png') no-repeat left top / 100%;
		}
	}
</style>